<?php

namespace JyUtils\Guard;

use JyUtils\Redis\Redis;
use JyUtils\Request\Request;

trait GuardUa
{
  /**
   * 添加ua黑名单
   *
   * @param string $uaValue UA值
   * @param int    $expire  失效时间, 留空为一年
   */
  public static function addBlackUa($uaValue = null, $expire = null)
  {
    $uaValue = $uaValue ?: Request::getUa();
    $name    = md5($uaValue);
    if ($expire) {
      $expire = strlen($expire) == 10 ? $expire : time() + $expire;
    } else if ($expire == -1) {
      $expire = 0;
    } else {
      $expire = time() + 31536000;
    }
    return Redis::hset(self::$table_black_ua, $name, [
      'value'  => $uaValue,
      'expire' => $expire,
    ]);
  }
  
  /**
   * 取当前UA黑名单列表
   *
   * @return array
   */
  public static function getUserAgenList()
  {
    $res  = Redis::hgetall(self::$table_black_ua);
    $list = [];
    foreach ($res as $ua) {
      $list[] = json_decode($ua, true);
    }
    return $list;
  }
  
  /**
   * ua是否在黑名单中
   *
   * @param string $uaValue UA值，留空将取当前请求的UA
   */
  private static function uaIsBlack($uaValue = null)
  {
    $uaValue = $uaValue ?: Request::getUa();
    $name    = md5($uaValue);
    
    // 未在黑名单中
    if (!$value = Redis::hget(self::$table_black_ua, $name)) {
      return false;
    }
    
    if ($value = json_decode($value, true)) {
      // 是否失效
      if ($value['expire'] < time()) {
        return Redis::hdel(self::$table_black_ua, $name);
      }
    }
    fail('请求异常，异常码(1000)');
  }
}
